/*
 * ListenerFile.cpp
 *
 *  Created on: Mar 16, 2009
 *      Author: Andrzej Olchawa
 *      mailto: andrzejolchawa@gmail.com
 *      http://www.hardtechnology.org
 *      This is a part of the Armazd project, which is covered by
 *      GNU GPL v2 license.
 */

#include "ListenerFile.h"
#include "HTFramework/HTThread.cpp"

ListenerFile::ListenerFile() {}

ListenerFile::ListenerFile(string name, string path)
{
	listenerName = name;
	this->path = path;
	start();
}

ListenerFile::~ListenerFile() {}

void ListenerFile::run()
{
	FILE *file = fopen(path.c_str(), "r");

	if (file)
	{
		fseek(file, 0, SEEK_END);
		char newStringLine[SIZE_OF_LISTENER_BUFFER];

		while (true)
		{
			if (!interrupt)
			{
				try
				{
					newStringLine[0] = '\0';
					while (fgets(newStringLine, SIZE_OF_LISTENER_BUFFER, file))
					{
						if (strlen(newStringLine) > 0)
						{
							sender->sendData(string(newStringLine));
						}
						newStringLine[0] = '\0';
					}
				}
				catch (AgentException &e)
				{
					e.printException();
				}
				sleep(1);
			}
		}

		fclose(file);
	}
	else
	{
		throw AgentException("ListenerFile.run: can't open file: "+ path);
	}
}
